<template>
  <div class="order-payment">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>仓库管理</h1>
      <div class="breadcrumb">仓库管理</div>
    </div>

    <!-- 搜索筛选区域 -->
    <div class="search-section">
      <div class="search-form">
        <div class="form-item">
          <label>仓库名称</label>
          <input v-model="searchForm.name" type="text" placeholder="请输入仓库名称" />
        </div>
        <div class="form-item">
          <label>负责人</label>
          <input v-model="searchForm.manager" type="text" placeholder="请输入负责人姓名" />
        </div>
        <div class="form-buttons">
          <button class="btn btn-primary" @click="searchWarehouses">查询</button>
          <button class="btn btn-secondary" @click="resetSearch">重置</button>
        </div>
      </div>
    </div>

    <!-- 操作按钮 -->
    <div class="action-bar">
      <button class="btn btn-primary" @click="openAddModal">新增仓库</button>
    </div>

    <!-- 仓库列表 -->
    <div class="table-container">
      <table class="data-table">
        <thead>
        <tr>
          <th><input type="checkbox" v-model="selectAll" @change="toggleSelectAll" /></th>
          <th>仓库名称</th>
          <th>仓库编码</th>
          <th>地址</th>
          <th>负责人</th>
          <th>状态</th>
          <th>创建时间</th>
          <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="warehouse in warehouseList" :key="warehouse.id">
          <td><input type="checkbox" v-model="warehouse.selected" /></td>
          <td>{{ warehouse.whName }}</td>
          <td>{{ warehouse.whCode }}</td>
          <td>{{ warehouse.address }}</td>
          <td>{{ warehouse.manager }}</td>
          <td>
            <span :class="getStatusClass(warehouse.status)">{{ getStatusText(warehouse.status) }}</span>
          </td>
          <td>{{ formatDate(warehouse.createdAt) }}</td>
          <td>
            <button class="btn btn-small btn-primary" @click="editWarehouse(warehouse)">编辑</button>
            <button class="btn btn-small btn-danger" @click="deleteWarehouse(warehouse.id)">删除</button>
          </td>
        </tr>
        <tr v-if="warehouseList.length === 0">
          <td colspan="8" class="text-center">暂无数据</td>
        </tr>
        </tbody>
      </table>
    </div>

    <!-- 分页 -->
    <div class="pagination" v-if="totalItems > 0">
      <div class="pagination-info">
        共{{ totalPages }}页/{{ totalItems }}条数据
      </div>
      <div class="pagination-controls">
        <button class="btn btn-page" :disabled="currentPage === 1" @click="changePage(currentPage - 1)">上一页</button>
        <button
            v-for="page in visiblePages"
            :key="page"
            class="btn btn-page"
            :class="{ active: page === currentPage }"
            @click="changePage(page)"
        >
          {{ page }}
        </button>
        <button class="btn btn-page" :disabled="currentPage === totalPages" @click="changePage(currentPage + 1)">下一页</button>
      </div>
      <div class="pagination-jump">
        <span>跳至</span>
        <input type="number" v-model="jumpPage" min="1" :max="totalPages" />
        <span>页</span>
        <button class="btn btn-small" @click="jumpToPage">确定</button>
      </div>
    </div>

    <!-- 仓库新增/编辑模态框 -->
    <div v-if="showWarehouseModal" class="modal-overlay" @click="showWarehouseModal = false">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>{{ isEdit ? '编辑仓库' : '新增仓库' }}</h3>
          <button class="modal-close" @click="showWarehouseModal = false">&times;</button>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label>仓库名称</label>
            <input type="text" v-model="warehouseForm.whName" placeholder="请输入仓库名称" />
          </div>
          <div class="form-group">
            <label>仓库编码</label>
            <input type="text" v-model="warehouseForm.whCode" placeholder="请输入仓库编码" />
          </div>
          <div class="form-group">
            <label>地址</label>
            <input type="text" v-model="warehouseForm.address" placeholder="请输入仓库地址" />
          </div>
          <div class="form-group">
            <label>负责人</label>
            <input type="text" v-model="warehouseForm.manager" placeholder="请输入负责人姓名" />
          </div>
          <div class="form-group">
            <label>状态</label>
            <select v-model="warehouseForm.status">
              <option :value="1">启用</option>
              <option :value="0">停用</option>
            </select>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary" @click="showWarehouseModal = false">取消</button>
          <button class="btn btn-primary" @click="submitWarehouse">确认</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { apiGet, apiPost, apiPut, apiDelete } from '../../utils/api.js'

// 响应式数据
const searchForm = reactive({
  name: '',
  manager: ''
})

const warehouseList = ref([])
const selectAll = ref(false)
const currentPage = ref(1)
const totalPages = ref(1)
const totalItems = ref(0)
const jumpPage = ref(1)
const showWarehouseModal = ref(false)
const isEdit = ref(false)

const warehouseForm = reactive({
  id: null,
  whName: '',
  whCode: '',
  address: '',
  manager: '',
  status: 1
})

// 计算属性
const visiblePages = computed(() => {
  const pages = []
  const start = Math.max(1, currentPage.value - 2)
  const end = Math.min(totalPages.value, currentPage.value + 2)

  for (let i = start; i <= end; i++) {
    pages.push(i)
  }

  return pages
})

// 方法
const searchWarehouses = async () => {
  console.log('搜索条件:', searchForm)
  await loadWarehouseData()
}

const resetSearch = async () => {
  searchForm.name = ''
  searchForm.manager = ''
  await loadWarehouseData()
}

const toggleSelectAll = () => {
  warehouseList.value.forEach(warehouse => {
    warehouse.selected = selectAll.value
  })
}

const changePage = async (page) => {
  currentPage.value = page
  await loadWarehouseData()
}

const jumpToPage = async () => {
  if (jumpPage.value >= 1 && jumpPage.value <= totalPages.value) {
    currentPage.value = jumpPage.value
    await loadWarehouseData()
  }
}

const getStatusClass = (status) => {
  return status === 1 ? 'status-paid' : 'status-unpaid'
}

const getStatusText = (status) => {
  return status === 1 ? '启用' : '停用'
}

const formatDate = (dateStr) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

const openAddModal = () => {
  isEdit.value = false
  warehouseForm.id = null
  warehouseForm.whName = ''
  warehouseForm.whCode = ''
  warehouseForm.address = ''
  warehouseForm.manager = ''
  warehouseForm.status = 1
  showWarehouseModal.value = true
}

const editWarehouse = (warehouse) => {
  isEdit.value = true
  warehouseForm.id = warehouse.id
  warehouseForm.whName = warehouse.whName
  warehouseForm.whCode = warehouse.whCode
  warehouseForm.address = warehouse.address
  warehouseForm.manager = warehouse.manager
  warehouseForm.status = warehouse.status
  showWarehouseModal.value = true
}

const deleteWarehouse = async (id) => {
  if (confirm('确定要删除此仓库吗？')) {
    try {
      const result = await apiDelete(`/ware-service/warehouse/${id}`)
      if (result && (result.code === 0 || result.status === 200 || result.status === 204)) {
        alert('仓库删除成功')
        await loadWarehouseData()
      } else {
        alert(result?.message || '仓库删除失败')
      }
    } catch (error) {
      console.error('删除仓库时出错:', error)
      alert('删除仓库时出错')
    }
  }
}

const submitWarehouse = async () => {
  try {
    if (isEdit.value) {
      const result = await apiPut(`/ware-service/warehouse/${warehouseForm.id}`, warehouseForm)
      if (result && (result.code === 0 || result.status === 200 || result.status === 204)) {
        alert('仓库更新成功')
        showWarehouseModal.value = false
        await loadWarehouseData()
      } else {
        alert(result?.message || '仓库更新失败')
      }
    } else {
      const result = await apiPost('/ware-service/warehouse', warehouseForm)
      if (result && (result.code === 0 || result.status === 200 || result.status === 201)) {
        alert('仓库添加成功')
        showWarehouseModal.value = false
        await loadWarehouseData()
      } else {
        alert(result?.message || '仓库添加失败')
      }
    }
  } catch (error) {
    console.error('提交仓库信息时出错:', error)
    alert('提交仓库信息时出错')
  }
}

const loadWarehouseData = async () => {
  try {
    const params = new URLSearchParams({
      page: currentPage.value,
      size: 10,
      ...(searchForm.name && { name: searchForm.name }),
      ...(searchForm.manager && { manager: searchForm.manager })
    })

    const data = await apiGet(`/ware-service/warehouse/list?${params}`)

    if (data.records) {
      warehouseList.value = data.records.map(warehouse => ({
        ...warehouse,
        selected: false
      }))
      totalPages.value = data.pages || 1
      totalItems.value = data.total || 0
      currentPage.value = data.current || 1
    } else {
      // 兼容后端返回数据结构不一致的情况
      warehouseList.value = (data.content || data || []).map(warehouse => ({
        ...warehouse,
        selected: false
      }))
      totalPages.value = data.totalPages || data.pages || 1
      totalItems.value = data.totalElements || data.total || data.length || 0
    }
  } catch (error) {
    console.error('加载仓库数据时出错:', error)
    warehouseList.value = []
    totalPages.value = 1
    totalItems.value = 0
  }
}

// 生命周期
onMounted(() => {
  loadWarehouseData()
})
</script>

<style scoped>
.order-payment {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.page-header {
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  color: #333;
}

.breadcrumb {
  color: #666;
  font-size: 14px;
}

.search-section {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 6px;
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  gap: 20px;
  align-items: flex-end;
  flex-wrap: wrap;
}

.form-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-item label {
  font-weight: 500;
  color: #333;
  font-size: 14px;
}

.form-item input,
.form-item select {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  min-width: 150px;
}

.form-buttons {
  display: flex;
  gap: 10px;
}

.action-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-end;
}

.table-container {
  overflow-x: auto;
  margin-bottom: 20px;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 14px;
}

.data-table th,
.data-table td {
  padding: 12px 8px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

.data-table th {
  background: #f8f9fa;
  font-weight: 600;
  color: #333;
}

.data-table tbody tr:hover {
  background: #f8f9fa;
}

.status-unpaid {
  color: #dc3545;
  font-weight: 500;
}

.status-partial {
  color: #ffc107;
  font-weight: 500;
}

.status-paid {
  color: #28a745;
  font-weight: 500;
}

.pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 0;
}

.pagination-info {
  color: #666;
  font-size: 14px;
}

.pagination-controls {
  display: flex;
  gap: 5px;
}

.pagination-jump {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination-jump input {
  width: 60px;
  padding: 4px 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
}

.btn-primary {
  background: #007bff;
  color: white;
}

.btn-primary:hover {
  background: #0056b3;
}

.btn-secondary {
  background: #6c757d;
  color: white;
}

.btn-secondary:hover {
  background: #545b62;
}

.btn-danger {
  background: #dc3545;
  color: white;
}

.btn-danger:hover {
  background: #c82333;
}

.btn-page {
  background: white;
  border: 1px solid #ddd;
  color: #333;
  padding: 6px 12px;
}

.btn-page:hover {
  background: #f8f9fa;
}

.btn-page.active {
  background: #007bff;
  color: white;
  border-color: #007bff;
}

.btn-page:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.btn-small {
  padding: 4px 8px;
  font-size: 12px;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  width: 500px;
  max-width: 90vw;
}

.modal-header {
  padding: 20px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  margin: 0;
  color: #333;
}

.modal-close {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #666;
}

.modal-body {
  padding: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
}

.form-group input,
.form-group select,
.form-group textarea {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.form-group textarea {
  height: 80px;
  resize: vertical;
}

.modal-footer {
  padding: 20px;
  border-top: 1px solid #eee;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
